package mini.util;

import java.util.HashMap;
import java.util.List;

import mini.Env;
import mini.Proc;
import mini.expr.Element;

public class MiniUtil {

	/**
	 * Creates a string to represent a nametable in order to aid debugging
	 **/
	public static String getNametableAsString( HashMap<String,Element> nametable ) {
		
		StringBuilder strbuf = new StringBuilder( "" );
		
		if( nametable != null ) {
			strbuf.append( "[");
			boolean needComma = false;
			for( String key : nametable.keySet() ) {
				if( needComma ) {
					strbuf.append(",");
				}
				strbuf.append( key + "=" + nametable.get(key) );
				needComma = true;
			}
			strbuf.append("]");
		}
		
		return strbuf.toString();
	}

	/**
	 * Given a list of environments, try to find this funcid. You start at the end of
	 * list of environments and work backward until you find a match (if you
	 * find a match);
	 * 
	 * @param listOfEnvs
	 * @param funcid
	 * @return
	 */
	public static Proc lookupFunction(List<Env> listOfEnvs, String funcid) {
		
		Proc proc = null;
		
		if( listOfEnvs != null ) {
			for( int i = listOfEnvs.size()-1; i >= 0 && proc==null; i-- ) {
				HashMap<String,Proc> functiontable = listOfEnvs.get(i).getFunctable();
				if( functiontable != null ) {
					proc = functiontable.get(funcid);
				}
			}
		}
		
		return proc;
	}

	/**
	 * Given a list of environment, try to find this symbol. You start at the end of
	 * list of environments and work backward until you find a match (if you
	 * find a match);
	 * 
	 * @param listOfEnvs
	 * @param name
	 * @return
	 */
	public static Element lookupSymbol(List<Env> listOfEnvs, String name) {
		
		Element elem = null;
		
		if( listOfEnvs != null ) {
			for( int i = listOfEnvs.size()-1; i >= 0 && elem==null; i-- ) {
				HashMap<String,Element> nametable = listOfEnvs.get(i).getNametable();
				if( nametable != null ) {
					elem = nametable.get(name);
				}
			}
		}
		
		return elem;
	}
}
